package com.ask.javabagubooster.a_java_basis.juc.blocked_queue;

import java.util.LinkedList;
import java.util.Queue;

public class TaskQueue {
    // 任务队列
    private final Queue<String> taskQueue = new LinkedList<>();
    // 锁对象
    private final Object lock = new Object();
    // 容量
    private final int capacity;

    // 构造函数

    public TaskQueue(int capacity) {
        this.capacity = capacity;
    }


    // put
    public void put(String task) throws InterruptedException {
        // 轮询队列是否有空位
        while (taskQueue.size() == capacity) {
            System.out.println("队列已满，生产者等待...");
            lock.wait();
        }
        taskQueue.add(task);
        lock.notifyAll();
    }

    // take
    public String take() throws InterruptedException {
        // 轮询队列中是否有资源
        while (taskQueue.isEmpty()) {
            System.out.println("队列为空, 消费者等待...");
            lock.wait();
        }
        String task = taskQueue.remove();
        lock.notifyAll();
        return task;
    }
}
